package com.kanshu.ksgb.fastread.doudou.module.book.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dl7.recycler.helper.RecyclerViewHelper;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.IGenrialMvpView;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.ReaderJumpConfig;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ActivityMgr;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookDetailsAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.SelectedBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.view.AdBookDetailsHeaderLayout;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.BookDetailsBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.download.activity.DownLoadChapterActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.NotifyBean;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadErrorLayout;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wcy on 2017\7\31 0031
 */
@Route(path = ARouterConfig.BOOK_DETAIL)
public class BookDetailActivity extends BaseActivity implements IGenrialMvpView<BaseResult<BookDetailsBean>> {

    public static final String EXTRA_BOOK_ID = "book_id";
    @BindView(R.id.recyler_view)
    RecyclerView mRecylerView;
    @BindView(R.id.join_shelf)
    TextView mJoinShelf;
    @BindView(R.id.swipe_refresh)
    TwinklingRefreshLayout mSwipeRefresh;
    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.bottom_container)
    FrameLayout mBottomContainer;
    @BindView(R.id.start_read)
    TextView mStartRead;
    private String mBookId;
    BookCityPresenter mBookCityPresenter;
    AdBookDetailsHeaderLayout mHeaderLayout;
    View mBookDetailsFooter;
    BookDetailsAdapter mAdapter;
    List<SelectedBookInfo> mInfos = new ArrayList<>();
    BookDetailsBean mDetailsBean;
    // 错误处理页面
    private BookReadErrorLayout mErrorLayout;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_details_layout);
        ButterKnife.bind(this);
        parseIntent();
        parseVipJpushChannel();
        init();
        setActivityTag();
    }

    private void init() {
        setTitle("书籍详情");
        mStartRead.setText(SettingManager.getInstance().isReadBook(mBookId) ? "继续阅读" :  "免费阅读");
        mSwipeRefresh.setPureScrollModeOn();
        mBookCityPresenter = new BookCityPresenter(lifeCyclerSubject);
        mBookCityPresenter.setBookDetailsView(this);
        mAdapter = new BookDetailsAdapter(mInfos);
        RecyclerViewHelper.initRecyclerViewV(this, mRecylerView, mAdapter);
        mBookCityPresenter.getBookDetails(mBookId);
        EventBus.getDefault().register(this);
        mEmptyLayout.setRetryListener(() -> mBookCityPresenter.getBookDetails(mBookId));
        AdPresenter.Companion.pvuvStatics("book_detail", mBookId);
        mTitle.getLeftContainer().setOnClickListener(v -> {
            returnToFirst();
        });
        mTitle.getRightContainer().setOnClickListener(view -> {
            Map<String, String> map = new HashMap<>();
            map.put("tab_index", ARouterConfig.HomePageParams.TAB_BOOK_CITY + "");
            map.put("sub_tab_index", Constants.BookCityTabType.TYPE_SELECTED + "");
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, map);
        });
        ImageView imageView = new ImageView(getActivity());
        imageView.setImageResource(R.mipmap.ic_home_btn);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL|Gravity.RIGHT;
        mTitle.getRightContainer().addView(imageView, params);
        DisplayUtils.visible(mTitle.getRightContainer());
    }

    /**
     * 设置Activity的tag
     */
    protected String getSpecifyTag(){
        return mBookId;
    }

    private void returnToFirst() {
        ActivityMgr.getInstance().returnToFirstOrFinish(BookDetailActivity.class, mBookId);
    }


    private void parseIntent() {
        mBookId = getIntent().getStringExtra(EXTRA_BOOK_ID);
        if (TextUtils.isEmpty(mBookId)) {
            dismissLoading();
            return;
        }
    }

    public void jumpReaderActivity(){
        ReaderInputParams params = new ReaderInputParams();
        params.book_id = mBookId;
        ReaderJumpConfig.startReaderActivity(getActivity(), params);
        mStartRead.setText("继续阅读");
    }

    protected void parseVipJpush(NotifyBean bean){
        mBookId = bean.notify_book_id;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleShelfEvent(ShelfEvent event) {
        switch (event.code) {
            case ShelfEvent.ADD_TO_SHELF_SUCCESS:
                BookInfo info = (BookInfo) event.obj;
                if (info != null && TextUtils.equals(info.book_id, mBookId)) {
                    mJoinShelf.setText("已加入书架");
                    mJoinShelf.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_added_shelf, 0, 0);
                    ToastUtil.showStaticMessage("加入书架成功");
                    mDetailsBean.book_info.join_bookcase = "1";
                }
                break;
            case ShelfEvent.ADD_TO_SHELF_FAIL:
                break;
            case ShelfEvent.DEL_FROM_SHELF_SUCCESS:
                List<String> book_ids = (List<String>) event.obj;
                for (String book_id : book_ids) {
                    if (book_id.equals(mDetailsBean.book_info.book_id)) {
                        mJoinShelf.setText("加入书架");
                        mDetailsBean.book_info.join_bookcase = "0";
                        mJoinShelf.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_detail_join_shelf, 0, 0);
                    }
                }
                break;
            default:
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHeaderLayout != null) {
            mHeaderLayout.recycle();
        }
        mBookCityPresenter.detachView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void finish() {
        Utils.jumpToHomeIfNeed();
        super.finish();
    }

    @Override
    public void showLoading(String s) {

    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    @Override
    public void showContent(BaseResult<BookDetailsBean> result) {
        dismissLoading();
        if (mHeaderLayout == null) {
            mHeaderLayout = new AdBookDetailsHeaderLayout(this);
            mBookDetailsFooter = LayoutInflater.from(this).inflate(R.layout.item_book_details_cpinfo_footer, null);
            mAdapter.addHeaderView(mHeaderLayout);
            mAdapter.addFooterView(mBookDetailsFooter);
        }
        if (result.result.data.cp_info != null && !TextUtils.isEmpty(result.result.data.cp_info.origin_company)) {
            TextView tv = mBookDetailsFooter.findViewById(R.id.cp_info);
            View infoTitle = mBookDetailsFooter.findViewById(R.id.cp_info_title);
            DisplayUtils.visible(tv, infoTitle);
            String s = getString(R.string.book_details_cp, result.result.data.cp_info.shelves_time, result.result.data.cp_info.origin_company, result.result.data.cp_info.target_company);
            tv.setText(s);
        } else {
            TextView tv = mBookDetailsFooter.findViewById(R.id.cp_info);
            View infoTitle = mBookDetailsFooter.findViewById(R.id.cp_info_title);
            DisplayUtils.gone(tv);
            DisplayUtils.invisible(infoTitle);
        }
        mHeaderLayout.refreshByBookInfo(result.result.data.book_info, result.result.data.last_chapter_info);
        wrapBookList(result.result.data);
        mAdapter.notifyDataSetChanged();
        mDetailsBean = result.result.data;
        if (mDetailsBean != null && mDetailsBean.book_info != null) {
            DisplayUtils.visible(mBottomContainer, mStartRead);
            if ("0".equals(mDetailsBean.book_info.join_bookcase)) {
                mJoinShelf.setText("加入书架");
                mJoinShelf.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_detail_join_shelf, 0, 0);
            } else {
                mJoinShelf.setText("已加入书架");
                mJoinShelf.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ic_added_shelf, 0, 0);
            }
        }
    }

    @Override
    public void showError(int errCode, String errDesc) {
        dismissLoading();
        int status = EmptyLayout.STATUS_NO_NET;
        if (errCode == Constants.ErrCode.NoData) {
            status = EmptyLayout.STATUS_NO_DATA;
        }
        if (mEmptyLayout != null) {
            mEmptyLayout.setEmptyStatus(status);
        }
        if (status == Constants.ErrCode.NetErr) {
            errDesc = getString(R.string.standard_net_tip);
        }
        ToastUtil.showStaticMessage(errDesc);
        if (errCode == Constants.ErrCode.Offline) {
            handleBookError(errCode);
        }
    }
    /**
     * 根据错误码处理阅读器页面
     * @param code
     */
    private void handleBookError(int code) {
        if (mErrorLayout == null) {
            ViewStub stub = findViewById(R.id.err_stub);
            if (stub != null) {
                View v = stub.inflate();
                mErrorLayout = v.findViewById(R.id.err_handle_container);
            }
        }
        if (mErrorLayout != null) {
            mErrorLayout.refreshByErrorCode(code);
            if (mEmptyLayout != null) {
                mEmptyLayout.hide();
            }
        }
    }

    @OnClick({R.id.join_shelf, R.id.download_bookinfo, R.id.start_read})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.join_shelf:
                if (mDetailsBean != null && mDetailsBean.book_info != null) {
                    BookPresenter presenter = new BookPresenter(lifeCyclerSubject);
                    if ("0".equals(mDetailsBean.book_info.join_bookcase)) {
                        presenter.joinBookShelf(mBookId);
                    } else {
                        presenter.delFromBookShelf(mBookId);
                    }
                }
                break;
            case R.id.download_bookinfo:
                if(!MMKVUserManager.getInstance().isUserLogin()){
                    ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "");
                }else {
                    DownLoadChapterActivity.actionStart(this, mBookId);
                }
                break;
            case R.id.start_read:
                jumpReaderActivity();
                break;
            default:
                break;
        }
    }

    private void wrapBookList(BookDetailsBean detailsBean) {
        if (!Utils.isEmptyList(detailsBean.like_book)) {
            SelectedBookInfo bookInfo = new SelectedBookInfo();
            bookInfo.type = SelectedBookInfo.TYPE_ONE;
            bookInfo.list = detailsBean.like_book;
            mInfos.add(bookInfo);
        }
        if (!Utils.isEmptyList(detailsBean.like_shudan)) {
            SelectedBookInfo bookInfo = new SelectedBookInfo();
            bookInfo.type = SelectedBookInfo.TYPE_TWO;
            bookInfo.list = detailsBean.like_shudan;
            mInfos.add(bookInfo);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        returnToFirst();
    }


}
